package com.fadadianqi.logistics.admin.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.Constants;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.goods.model.BrandCategoryRelation;
import com.fadadianqi.goods.model.Category;
import com.fadadianqi.goods.model.Properties;
import com.fadadianqi.goods.service.GoodsService;
import com.yeqiangwei.commons.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static com.fadadianqi.logistics.admin.controller.URIMappingUtils.INVENTORY_PREFIX;

@Controller("admin_categoryController")
public class CategoryController {

    private static final Log log = LogFactory.getLog(CategoryController.class);

    private static final String URI_AJAX_SAVE = INVENTORY_PREFIX + "/ajax/category/save";
    private static final String URI_AJAX_GET = INVENTORY_PREFIX + "/ajax/category/{id}";

    private static final String COMMAND_NAME = "categoryForm";

    private static final String URI_AJAX_LIST = INVENTORY_PREFIX + "/ajax/category/list";
    private static final String VIEW_AJAX_LIST = "admin/category/ajaxList";
    @Resource(name = "goodsService")
    private GoodsService goodsService;

    private List<Category> autoFindCategory(String brandId) {
        List<Category> list = null;
        if (ValidatorHelper.isNotEmpty(brandId)) {
            List<BrandCategoryRelation> bcrList = goodsService.findRelationCategory(brandId);
            if (ValidatorHelper.isNotEmpty(bcrList)) {
                list = new ArrayList<Category>();
                for (BrandCategoryRelation bcr : bcrList) {
                    Category c = goodsService.getCategoryById(bcr.getCategoryId());
                    list.add(c);
                }
            }
        } else {
            list = goodsService.findAllCategory();
        }
        return list;
    }

    /**
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/a/category/autoShow")
    public String autoShow(HttpServletRequest request, ModelMap modelMap) {
        String cid = ParamUtils.getString(request, "cid", null);
        modelMap.put("cid", cid);
        String prefixURI = ParamUtils.getString(request, "pf", null);
        modelMap.put("prefixURI", prefixURI);
        String bid = ParamUtils.getString(request, "bid", null);
        modelMap.put("bid", bid);
        List<Category> list = autoFindCategory(bid);
        modelMap.put("categoryList", list);
        return "/admin/category/autoShow";
    }

    /**
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/a/category/ajax/autoShow", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> ajaxAutoShow(HttpServletRequest request, ModelMap modelMap) {
        String bid = ParamUtils.getString(request, "bid", null);
        List<Category> list = autoFindCategory(bid);
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = new AjaxResult(list, Boolean.TRUE, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/a/category/props/list", method = RequestMethod.GET)
    public String showProps(HttpServletRequest request, ModelMap modelMap) {

        List<Category> categoryList = null;

        categoryList = goodsService.findAllCategory();

        modelMap.put("categoryList", categoryList);

        List<CategoryVO> categoryVOList = new ArrayList<CategoryVO>();
        if (ValidatorHelper.isNotEmpty(categoryList)) {
            for (Category c : categoryList) {
                CategoryVO vo = new CategoryVO();
                BeanUtils.copyProperties(vo, c);
                List<Properties> props = goodsService.findPropsByCategory(c);
                vo.setProps(props);
                categoryVOList.add(vo);
            }
            modelMap.put("categoryVOList", categoryVOList);
        }
        return "/admin/category/propsList";
    }

    @RequestMapping(value = "/a/category/list", method = RequestMethod.GET)
    public String showList(HttpServletRequest request, ModelMap modelMap) {
        String flt = com.yeqiangwei.commons.util.ParamHelper.getString(request, "flt", null);
        int total = goodsService.countCategoryByFirstLetter(flt);
        Pagination pagination = new Pagination(request, 100);
        List<Category> categoryList = goodsService.findCategoryByFirstLetter(flt, pagination);
        pagination.setTotal(total);
        PaginationHelper.setAttribute(request, pagination);
        modelMap.put("categoryList", categoryList);
        modelMap.put("alphabet", Constants.ALPHABET);
        return "/admin/category/list";
    }

    @RequestMapping(value = "/a/ajax/category/modify/list", method = RequestMethod.GET)
    public String ajaxModifyListList(HttpServletRequest request, ModelMap modelMap) {
        String flt = com.yeqiangwei.commons.util.ParamHelper.getString(request, "flt", null);
        int total = goodsService.countCategoryByFirstLetter(flt);
        Pagination pagination = new Pagination(request, 100);
        List<Category> categoryList = goodsService.findCategoryByFirstLetter(flt, pagination);
        pagination.setTotal(total);
        PaginationHelper.setAttribute(request, pagination);
        modelMap.put("categoryList", categoryList);
        return "/admin/category/ajaxModifyList";
    }

    @RequestMapping(value = URI_AJAX_GET, method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> ajaxGet(@PathVariable String id) {

        Category category = goodsService.getCategoryById(id);

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");


        AjaxResult rs = new AjaxResult(category, Boolean.TRUE, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = URI_AJAX_LIST, method = RequestMethod.GET)
    public String ajaxList(HttpServletRequest request, ModelMap model) {
        List<Category> list = goodsService.findAllCategory();

        model.addAttribute("categoryList", list);
        return VIEW_AJAX_LIST;
    }

    @RequestMapping(value = URI_AJAX_SAVE, method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> ajaxSave(
            @ModelAttribute(COMMAND_NAME) Category category
            , BindingResult result, SessionStatus status) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = null;

        category.setPinyin(StringHelper.toPinyin(category.getName()));

        if (ValidatorHelper.isEmpty(category.getId())
                && goodsService.getCategoryByName(category.getName()) != null) {
            String tmp = category.getName() + " 品类已经存在！！！";
            rs = new AjaxResult(category, Boolean.FALSE, tmp);
        } else {
            goodsService.saveCategory(category);
            rs = new AjaxResult(category, Boolean.TRUE, null);
        }
        status.setComplete();
        if (log.isDebugEnabled()) {
            log.debug("#ajaxSave#, id: " + category.getId()
                    + ", name: " + category.getName());
        }
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.CREATED);
    }

    public class CategoryVO extends Category {

        /**
         *
         */
        private static final long serialVersionUID = 8162288685519636757L;

        private List<Properties> props;

        public List<Properties> getProps() {
            return props;
        }

        public void setProps(List<Properties> props) {
            this.props = props;
        }
    }
}
